<template>
<div class="divCheckListComponent divWarehouse">
    <div class="divContent box">
      <div class="tableInfo">
        <base-button
          class="importantButton"
          @click="btnAddCheckListClick"
        >添加盘点清单</base-button>
        <base-button
          class="unimportanceButton"
          @click="btnBatchDeleteClick"
        >删除盘点清单</base-button>
      </div>
      <div class="divTableTitle" v-if="tableTitle.checkedArr.length > 0">
            <span class="spanLabel">库位</span><span class="spanValue">{{tableTitle.sumLocation}}个</span>
            <span class="spanLabel">货品</span><span class="spanValue">{{tableTitle.sumGoods}}个</span>
      </div>
      <div  v-if="tableData.length>0">
        <el-table
          :data="tableData"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{ background: '#f9f6ee' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
              type="selection"
              align="center"
              width="55">
          </el-table-column>
          <el-table-column
            type="index"
            align="center"
            width="68"
            label="序号"
          />
          <el-table-column
            prop="warehouseName"
            align="center"
            label="仓库名称"
            width="160"
          />
          <el-table-column
            prop="areaName"
            align="center"
            label="库区名称"
            width="150"
          />
          <el-table-column
            prop="locationName"
            align="center"
            label="库位名称"
            width="160"
          >
          </el-table-column>
          <el-table-column
            prop="goodsName"
            align="center"
            label="货品名称"
            width="160"
          />
          <el-table-column
            prop="goodsCode"
            align="center"
            label="货品编码"
            width="160"
          />
          <el-table-column
            prop="goodsBarCode"
            align="center"
            label="货品条码"
            width="160"
          >
          </el-table-column>
          <el-table-column
            prop="ownerName"
            align="center"
            label="货主名称"
            width="160"
          >
          </el-table-column>
          <el-table-column
            prop="stockNum"
            align="center"
            label="库存数量"
            width="160"
          >
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{row}">
              <base-button class="fontOperateButton"  @click="btnDeleteClick([row.id])">删除</base-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <base-pagination :total="paging.total" :limit="paging.size" @current-change="handleCurrentChange"  @size-change="handleSizeChange"></base-pagination>
        <base-dialog    :title="delDialogData.title"
                        :visible="delDialogData.visible"
                        :msg="delDialogData.msg"
                        @btn-cancle-click="delDialogData.visible= false"
                        @btn-sure-click ="btnDeleteSureClick"
        ></base-dialog>
      </div>
      <div
        v-else
        class="emptyTip"
      >
        <span class="imgIcon"></span>
        <p>暂无盘点清单</p>
      </div>
    </div>
    <div class="buttonBox">
      <base-button
        class="unimportanceButton"
        @click="btnReturnClick"
      >返回</base-button>
      <base-button
        class="minorImportantButton"
        @click="btnSaveClick"
      >提交</base-button>
    </div>
    <el-dialog title="添加盘点清单" :visible.sync="dialogData.visible" class="divDialog">
          <div>
            <div class="divDialogHead">
              <el-form   ref="ruleForm" :inline="true">
                <el-row :gutter="30" v-if="dimension === 'KW' ">
                  <el-col :span="8" >
                    <div class="divLable">库位名称</div>
                    <el-input
                      placeholder="请输入"
                      v-model="dialogData.searchParams.locationName"
                    />
                  </el-col>
                  <el-col :span="8" >
                    <div class="divLable">库位编号</div>
                    <el-input
                      placeholder="请输入"
                      v-model="dialogData.searchParams.locationCode"
                    />
                  </el-col>
                  <el-col :span="8">
                    <div class="divLable"></div>
                    <div class="textRight" style="margin-top: 16px;">
                      <base-button
                        class="minorImportantButton btnCancle"
                        @click="btnSearchClick"
                      >搜索</base-button>
                      <base-button class="unimportanceButton" @click="btnResetClick">重置</base-button>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="30" v-if="dimension === 'HP' ">
                  <el-col :span="12">
                    <div class="divLable">货品名称</div>
                    <el-input
                      placeholder="请输入"
                      v-model="dialogData.searchParams.goodsName"
                    />
                  </el-col>
                  <el-col :span="12">
                    <div class="divLable"></div>
                    <div class="textRight" style="margin-top: 16px;">
                      <base-button
                        class="minorImportantButton btnCancle"
                        @click="btnSearchClick"
                      >搜索</base-button>
                      <base-button class="unimportanceButton" @click="btnResetClick">重置</base-button>
                    </div>
                  </el-col>
                </el-row>
              </el-form>
              </div>
            <div  v-if="dialogData.tableData.length>0">
                <div class="divTableTitle" v-if="dialogData.checkedArr.length > 0">
                    <span class="spanLabel">当前已选</span><span class="spanValue">{{dialogData.checkedNum}}个货品</span>
                </div>
              <el-table
                :data="dialogData.tableData"
                stripe
                border
                style="width: 100%"
                ref="dialogTable"
                v-loading="loading"
                :header-cell-style="{ background: '#f9f6ee' }"
                @selection-change="dialogHandleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  align="center"
                  width="55"
                  :selectable="selectEnable"
                />
                <el-table-column
                  type="index"
                  align="center"
                  width="68"
                  label="序号"
                />
                <el-table-column
                  prop="locationName"
                  align="center"
                  label="仓库名称"
                  width="160"
                />
                <el-table-column
                  prop="areaName"
                  align="center"
                  label="库区名称"
                  width="150"
                />
                <el-table-column
                  prop="locationCode"
                  align="center"
                  label="库位编号"
                  width="160"
                >
                </el-table-column>
                <el-table-column
                  prop="locationName"
                  align="center"
                  label="库位名称"
                  width="160"
                />
                <el-table-column
                  prop="goodsName"
                  align="center"
                  label="货品名称"
                  width="160"
                />
                <el-table-column
                  prop="goodsCode"
                  align="center"
                  label="货品编号"
                  width="160"
                >
                </el-table-column>
                <el-table-column
                  prop="goodsBarCode"
                  align="center"
                  label="货品条码"
                  width="160"
                >
                </el-table-column>
                <el-table-column
                  prop="ownerName"
                  align="center"
                  label="货主名称"
                  width="160"
                >
                </el-table-column>
                <el-table-column
                  prop="free"
                  align="center"
                  label="库存数量"
                  width="160"
                >
                </el-table-column>
              </el-table>
              <!-- 分页 -->
              <base-pagination :total="dialogData.paging.total" :limit="dialogData.paging.size" @current-change="handleDialogCurrentChange"  @size-change="handleDialogSizeChange"></base-pagination>
            </div>
            <div
              v-else
              class="emptyTip"
            >
              <span class="imgIcon"></span>
              <p>暂无库存</p>
            </div>
        </div>
            <span slot="footer" class="dialog-footer">
                <base-button  @click="dialogData.visible = false" class="unimportanceButton" style="margin-right:20px">取消</base-button>
                <base-button @click="btnSureAddClick" class="minorImportantButton"  >确认添加</base-button>
            </span>
    </el-dialog>
</div>
</template>

<script lang="ts">
import SinglePage from '@/mixin/single-page'
import { mixins } from 'vue-class-component'
import { Component, Prop } from 'vue-property-decorator'
import BaseButton from '@/components/base-button/index.vue'
import BasePagination from '@/components/base-pagination/index.vue'
import { ICheckListTableData } from '@/module-storage/interface/check-list'
import { batchAllCheckList, deleteCheckList, findCheckListDetailsPaging, findSelectedCheckList, deleteCheckListByMasterId } from '@/module-storage/api/check-list'
import { getStorageDetailPaging } from '@/module-storage/api/storage'
import { IStorageTableData } from '@/module-storage/interface/storage'
import { ICommonReturn } from '@/utils/common-interface'
import BaseDialog from '@/components/base-dialog/index.vue'

@Component({
  name: 'ComponentCheckList',
  components: {
    BaseButton,
    BasePagination,
    BaseDialog
  }
})

export default class extends mixins(SinglePage) {
    @Prop({ default: null }) private ownerId !: string

    @Prop({ default: '' }) private dimension !: string

    @Prop({ default: null }) private masterId !: number

    @Prop({ default: null }) private areaId !: number

    private tableData: ICheckListTableData[] = []

    private loading = false

    private paging = {
      current: 1, // 当前页码
      size: 10, // 每页数据量
      total: 0
    }

    private dialogData = {
      visible: false,
      locationNum: 0,
      goodsNum: 0,
      title: '添加盘点单',
      tableData: [],
      searchParams: {
        locationName: '',
        locationCode: '',
        goodsName: ''
      },
      paging: {
        current: 1, // 当前页码
        size: 10, // 每页数据量
        total: 0
      },
      checkedArr: [] as number[],
      checkedNum: 0,
      selectedIds: [] as number[]
    }

    private tableTitle={
      sumLocation: 0, // 总计多少件
      sumGoods: 0, // 总计多少体积
      checkedArr: [] as ICheckListTableData[]
    }

    // 删除弹出框
    private delDialogData = {
      title: '确认删除',
      visible: false,
      msg: '',
      ids: [] as number[]
    }

    created() {
      this.initData()
    }

    initData() {
      new Promise((resolve) => {
        this.deleteList(resolve)
      }).then(() => {
        this.getList()
      })
    }

    private async deleteList(resolve:any) {
      const parent = (this.$parent as any)
      const map:Map<string, string> = parent.map
      if (map.size > 1) {
        await deleteCheckListByMasterId({ masterId: this.masterId })
        map.clear()
        map.set(this.dimension, this.dimension)
        parent.map = map
      }
      resolve()
    }

    private async getList() {
      this.loading = true
      const current = this.paging.current
      const size = this.paging.size
      const { data } = await findCheckListDetailsPaging({
        masterId: this.masterId,
        current,
        size
      })
      this.loading = false
      this.tableData = data.records
      this.paging.total = parseInt(data.total, 10)
    }

    private handleCurrentChange(page:number) {
      this.paging.current = page
      this.getList()
    }

    private handleSizeChange(page:number) {
      this.paging.size = page
      this.paging.current = 1
      this.getList()
    }

    private async getDialogList() {
      const dialogData = this.dialogData
      const current = dialogData.paging.current
      const size = dialogData.paging.size
      const search = this.dialogData.searchParams
      let params
      if (this.dimension === 'KW') {
        params = {
          areaId: this.areaId,
          locationCode: search.locationCode,
          locationName: search.locationName,
          current,
          size,
          needFree: 1
        }
      } else {
        params = {
          ownerId: this.ownerId,
          goodsName: search.goodsName,
          current,
          size,
          needFree: 1
        }
      }
      const { data } = await getStorageDetailPaging(params)
      this.dialogData.tableData = data.records
      this.dialogData.paging.total = parseInt(data.total, 10)
      this.dialogData.visible = true
    }

    private handleDialogCurrentChange(page:number) {
      this.dialogData.paging.current = page
      this.getDialogList()
    }

    private handleDialogSizeChange(page:number) {
      this.dialogData.paging.size = page
      this.dialogData.paging.current = 1
      this.getDialogList()
    }

    private btnAddCheckListClick() {
      this.btnResetClick()
    }

    private btnReturnClick() {
      (this.$parent as any).activeStep = 0
    }

    private btnResetClick() {
      this.dialogData.searchParams = {
        locationName: '',
        locationCode: '',
        goodsName: ''
      }
      this.dialogData.paging = {
        current: 1, // 当前页码
        size: 10, // 每页数据量
        total: 0
      }
      this.getDialogList()
    }

    private btnSaveClick() {
      (this.$parent as any).activeStep = 2
      this.closeWindow()
    }

    private btnSearchClick() {
      this.getDialogList()
    }

    private getTableTitleData() {
      let sumGoods = 0
      this.tableTitle.checkedArr.forEach((item:ICheckListTableData) => {
        sumGoods += Number(item.stockNum)
      })
      this.tableTitle.sumGoods = sumGoods
      this.tableTitle.sumLocation = this.tableTitle.checkedArr.length
    }

    private handleSelectionChange(itemList:ICheckListTableData[]) {
      this.tableTitle.checkedArr = itemList
      this.getTableTitleData()
    }

    private dialogHandleSelectionChange(itemList:IStorageTableData[]) {
      const idList = itemList.map((item) => {
        return item.id
      })
      this.dialogData.checkedArr = idList
      this.dialogData.checkedNum = idList.length
    }

    private selectEnable(row:IStorageTableData) {
      let flag = true
      this.dialogData.selectedIds.forEach(item => {
        if (item === row.id) {
          flag = false
        }
      })
      return flag
    }

    // 确认添加
    private async btnSureAddClick() {
      const idList:number[] = this.dialogData.checkedArr
      if (idList.length === 0) {
        this.$message.error('请勾选商品')
      } else {
        const data = ((await batchAllCheckList({
          stockIds: idList,
          masterId: this.masterId
        })) as unknown) as ICommonReturn
        if (data.code === 0) {
          this.$message.success(idList.length + '条添加成功')
          this.dialogData.visible = false
          this.getList()
          this.getSelectedList();
          (this.$refs.dialogTable as any).clearSelection()
        } else {
          this.$message.error(data.msg)
        }
      }
    }

    private async getSelectedList() {
      const { data } = await findSelectedCheckList({ masterId: this.masterId })
      this.dialogData.selectedIds = data
    }

    private btnDeleteClick(ids:[]) {
      if (this.confirmMsg()) {
        return
      }
      this.delDialogData.ids = ids
      this.delDialogData.visible = true
      this.delDialogData.msg = '确定要删除这' + ids.length + '项清单吗？'
    }

    private async btnDeleteSureClick() {
      const ids = this.delDialogData.ids
      const data = ((await deleteCheckList({ ids: ids })) as unknown) as ICommonReturn
      if (data.code === 0) {
        this.$message.success('删除成功')
        this.delDialogData.visible = false
        this.getList()
        this.getSelectedList()
        const checkedArr = this.tableTitle.checkedArr
        if (checkedArr.length === ids.length) {
          this.tableTitle.checkedArr = []
        } else {
          this.tableTitle.checkedArr = checkedArr.filter(x => ids.find(y => x.id !== y))
          this.getTableTitleData()
        }
        this.delDialogData.ids = []
      } else {
        this.$message.error(data.msg)
      }
    }

    private btnBatchDeleteClick() {
      if (this.confirmMsg()) {
        return
      }
      const checkedArr = this.tableTitle.checkedArr
      if (checkedArr.length === 0) {
        this.$message.error('请选择货品')
      } else {
        this.delDialogData.ids = checkedArr.map((item:ICheckListTableData) => {
          return item.id
        })
        this.delDialogData.visible = true
        this.delDialogData.msg = '确定要删除这' + checkedArr.length + '项清单吗？'
      }
    }
}
</script>
<style lang="scss" scoped>
.divCheckListComponent{
  .divLable{
    margin-bottom:10px
  }
  .divTableTitle{
      margin-bottom: 20px;
      background: #FFF9EB;
      border: 1px solid #FFB200;
      height: 32px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      line-height: 32px;
      padding-left: 9px;
      width: fit-content;
      .spanLabel{
        color: #332929;
        margin-right: 9px;
      }
      .spanValue{
        padding-right: 18px;
        color: #FFB200;
      }
    }
  .divDialog{
    .textRight{
      margin-top: 10px;
    }
    .emptyTip{
      border: 0;
    }
  }
    .divDialog{
        .divDialogHead{
            margin-bottom: 20px;
            .divLable{
                padding-bottom: 10px;
            }
        }
    }

}
</style>
